package com.example.demo.configs;

import com.example.demo.exceptions.handlers.CustomAsyncExceptionHandler;
import com.example.demo.properties.MyAsnyProperties;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;

/**
 * 定义相关操作
 */
@EnableAsync
@Configuration
public class AsynConfig  extends AsyncConfigurerSupport {

    @Autowired
    private MyAsnyProperties myAsnyProperties;


    /**
     * 初始化自定义异步线程池
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor asyncExecutor(){
        ThreadPoolTaskExecutor  executor=new ThreadPoolTaskExecutor ();
        executor.setCorePoolSize(myAsnyProperties.getMin());
        executor.setMaxPoolSize(myAsnyProperties.getMax());
        executor.setWaitForTasksToCompleteOnShutdown(myAsnyProperties.isWait());
        executor.setAwaitTerminationSeconds(60*15);
        return executor;
    }


    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }

    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor();
    }
}
